
import os
import time
import operator
import uuid
import rarfile
import zipfile
# 籤合
from customer import models
from method.method import case, WorkflowError, work_build
import wfs.function.produce_pdf as pf
from django.conf import settings
from django.db import transaction
import requests


os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'


def dec_id(target_id, all_id):
    """
    判断输入id是否在数据库
    :param target_id:
    :param all_id:
    :return:
    """
    k = 0
    if target_id:
        for i, v in enumerate(all_id):
            for n, m in v.items():
                if int(target_id) == m:
                    k = 1
    return target_id, k


def max_id(id):
    id_list = []
    if id:
        for i, v in enumerate(id):
            for n, m in v.items():
                id_list.append(m)
    return max(id_list)


# 只解壓pdf
def un_file(file_path, target_path, file_type):
    """
    解压文件
    :param file_path:
    :param target_path:
    :param file_type:
    :return:
    """
    listName = []
    fileName = {}
    filedir = {}
    no_pdf = 1
    if file_type == 'zip':
        fzip = zipfile.ZipFile(file_path, 'r')
        for fz in fzip.namelist():
            if str(fz).split('.')[-1] == 'pdf':
                gg = fz.encode(encoding="cp437")
                kk = gg.decode(encoding="gbk")
                new_name_zip = str(uuid.uuid1()) + '.' + str(fz).split('.')[-1]
                listName.append(new_name_zip)
                f_new = os.path.join(target_path, new_name_zip)
                file = open(f_new, 'wb')
                file.write(fzip.read(fz))
                file.close()
                fileName[kk] = new_name_zip
                filedir[kk] = os.path.getsize(f_new)
            else:
                no_pdf = 0
        os.remove(file_path)

    if file_type == 'rar':
        frar = rarfile.RarFile(file_path, 'r')
        for fr in frar.namelist():
            if str(fr).split('.')[-1] == 'pdf':
                new_name_rar = str(uuid.uuid1()) + '.' + str(fr).split('.')[-1]
                listName.append(new_name_rar)
                f_new = os.path.join(target_path, new_name_rar)
                file = open(f_new, 'wb')
                file.write(frar.read(fr))
                file.close()
                fileName[fr] = new_name_rar
                filedir[fr] = os.path.getsize(f_new)
            else:
                no_pdf = 0
        os.remove(file_path)

    return fileName, filedir, listName, no_pdf


# 不分類型解壓文件
def un_file_notype(file_path, target_path, file_type):
    """
    解压文件
    :param file_path:
    :param target_path:
    :param file_type:
    :return:
    """
    listName = []
    fileName = {}
    filedir = {}
    no_pdf = 1
    if file_type == 'zip':
        fzip = zipfile.ZipFile(file_path, 'r')
        for fz in fzip.namelist():
            fz = str(fz)
            gg = fz.encode(encoding="cp437")
            kk = gg.decode(encoding="gbk")
            new_name_zip = str(uuid.uuid1()) + '.' + str(fz).split('.')[-1]
            listName.append(new_name_zip)
            f_new = os.path.join(target_path, new_name_zip)
            file = open(f_new, 'wb')
            kp = fzip.read(fz)
            file.write(kp)
            file.close()
            fileName[kk] = new_name_zip
            filedir[kk] = os.path.getsize(f_new)
        os.remove(file_path)

    if file_type == 'rar':
        frar = rarfile.RarFile(file_path, 'r')
        for fr in frar.namelist():
            new_name_rar = str(uuid.uuid1()) + '.' + str(fr).split('.')[-1]
            listName.append(new_name_rar)
            f_new = os.path.join(target_path, new_name_rar)
            file = open(f_new, 'wb')
            file.write(frar.read(fr))
            file.close()
            fileName[fr] = new_name_rar
            filedir[fr] = os.path.getsize(f_new)
        os.remove(file_path)

    return fileName, filedir, listName


# 生成客戶圖紙的ecn編號
def ecn_no_num(be):
    ecn_time = time.strftime('%Y%m%d', time.localtime(time.time()))
    if be is None:
        ecn_no = 'ECN_C' + str(ecn_time) + '0001'
    elif len(be) != 17:
        ecn_no = 'ECN_C' + str(ecn_time) + '0001'
    else:
        sp = be[5:13]
        kp = be[13:]
        if operator.eq(sp, ecn_time):
            kp_new = int(kp) + 1
            ecn_no = be[:13] + str(kp_new).rjust(4, '0')
        else:
            ecn_no = 'ECN_C' + str(ecn_time) + '0001'
    return ecn_no


# 生成工程圖紙的ecn編號
def ecn_pro_num(be):
    ecn_time = time.strftime('%Y%m%d', time.localtime(time.time()))
    if be is None:
        ecn_no = 'ECN_E' + str(ecn_time) + '0001'
    elif len(be) != 17:
        ecn_no = 'ECN_E' + str(ecn_time) + '0001'
    else:
        sp = be[5:13]
        kp = be[13:]
        if operator.eq(sp, ecn_time):
            kp_new = int(kp) + 1
            ecn_no = be[:13] + str(kp_new).rjust(4, '0')
        else:
            ecn_no = 'ECN_E' + str(ecn_time) + '0001'
    return ecn_no


# 調用 ecn_no_num
def c_ecn(mid):
    if list(mid) != []:
        max_id_customer = max(mid)
        before_ecn = models.TbCustomerPaper.objects.filter(id=max_id_customer).values('ecn_no')[0]['ecn_no']
        ecn_no = ecn_no_num(str(before_ecn))
    else:
        ecn_time = time.strftime('%Y%m%d', time.localtime(time.time()))
        ecn_no = 'ECN_C' + str(ecn_time) + '0001'
    return ecn_no


# 調用 ecn_pro_num
def p_ecn(mid):
    if mid != []:
        max_id_customer = max(mid)
        before_ecn = models.TbProjectPaper.objects.filter(id=max_id_customer).values('ecn_no')[0]['ecn_no']
        ecn_no = ecn_pro_num(str(before_ecn))
    else:
        ecn_time = time.strftime('%Y%m%d', time.localtime(time.time()))
        ecn_no = 'ECN_E' + str(ecn_time) + '0001'
    return ecn_no


# 複製文件
def copy_data(model, i):
    str = 'models.{0}.objects.get(id=int({1}))'.format(model, i)
    # sf = models.TbDrawingFile.objects.get(id=int(i))
    sf = eval(str)
    sf.id = None
    sf.save()
    return sf


# put統計所有客戶信息
def customer_info(all_info, kk, name):
    c_list = []
    if name:
        for cn in all_info.values(name):
            for ke, v1 in cn.items():
                if str(v1) != kk.values(name)[0][name]:
                    c_list.append(v1)
    return c_list


# post 統計客戶信息
def cus_post(all_info, name):
    clist = []
    for i in all_info.values(name):
        for ke, ve in i.items():
            clist.append(ve)
    return clist


# 布尔转换
def bool_turn(d, values):
    """
    :return:
    """
    if d[values] == 0:
        va = False
        d[values] = va
        return va
    elif d[values] == 1:
        va = True
        d[values] = va
        return va


# 签合
def doc_check(a_id,pdf_list, file_applicate, workflow, n, form_id):
    """
    :return:
    """

    # 路由签合
    time_s = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 创建时间
    # file_applicate = request.user
    apply = models.TbApplyform.objects.create(pdf=pdf_list, apply_time=time_s,
                                              applicant=file_applicate)
    apply_id = apply.id  # 獲取剛創建的id
    apply_object = models.TbApplyform.objects.filter(id=apply_id)  # 獲取剛創建的字段的對象
    apply_object.update(customer=int(a_id.id))
    apply_object.update(degree='general')
    apply_object.update(layout='vertical')
    apply_object.update(apply_type='false')
    # 造就新的card_id字段
    kp = models.TbCustomerPaper.objects.filter(id=int(a_id.id)).values('ecn_no')[0]['ecn_no']
    apply_object.update(card_id=kp)
    apply_object.update(form=int(form_id))  # 只更新form_id 還有幾個字段通過form_id來找
    wf, mess = work_build(eval(workflow), '', 'sssss', kp, file_applicate, form_id, customer_id=a_id.id, project_id=None)
    apply_object.update(wrecord=wf)
    pf.form_pdf(wf, n)

def doc_check1(a_id,pdf_list, file_applicate, workflow, n, form_id):
    """
    :return:
    """

    # 路由签合
    time_s = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 创建时间
    apply = models.TbApplyform.objects.create(pdf=pdf_list, apply_time=time_s,
                                              applicant=file_applicate)
    apply_id = apply.id  # 獲取剛創建的id
    apply_object = models.TbApplyform.objects.filter(id=apply_id)  # 獲取剛創建的字段的對象
    apply_object.update(project=int(a_id.id))
    apply_object.update(degree='general')
    apply_object.update(layout='vertical')
    apply_object.update(apply_type='false')
    kp = models.TbProjectPaper.objects.filter(id=int(a_id.id)).values('ecn_no')[0]['ecn_no']
    apply_object.update(card_id=kp)
    apply_object.update(form=int(form_id))  # 只更新form_id 還有幾個字段通過form_id來找
    wf, mess = work_build(eval(workflow), '', 'sssss', kp, file_applicate, form_id,customer_id=None,project_id=a_id.id)
    apply_object.update(wrecord=wf)
    pf.form_pdf(wf, n)


# c_put
def c_put(all_data):
    modify_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    am = all_data[20]
    m = all_data[20].values('id')[0]['id']

    # 立即失效
    if all_data[25]:
        # 如果valid爲1,修改上一版本圖紙的 enabled 爲0fh
        # copy_id = request.POST.get('copy_id')
        if all_data[24]:
            models.TbCustomerPaper.objects.filter(copy_id=all_data[24], c_confirm__gte=2).update(enabled=0)
    if all_data[14] and all_data[27] == 'true':
        re_id = 1
        data = {"id": all_data[28], "action": "pass"}
        r = requests.post(settings.DOWNLOAD_URL + 'api/workflow_approval',
                      data=data, headers={'X-CSRFToken': all_data[29]})
        b = models.TbCustomerPaper.objects.get(id=m)
        # 更新客户信息
        mm = models.TbCustomerPaper.objects.filter(id=int(b.id))
        # 記錄變更次數
        c_info = models.TbCustomInfo.objects.filter(id=int(all_data[13]))
        mm.update(customer_info=int(c_info.values('id')[0]['id']))
        models.TbCustomerPaper.objects.filter(id=b.id).update(
            c_name=str(c_info.values('c_name')[0]['c_name']))
        models.TbCustomerPaper.objects.filter(id=b.id).update(
            c_type=str(c_info.values('c_type')[0]['c_type']))
        # 更新输入的字段
        cu = models.TbCustomerPaper.objects.filter(id=int(b.id))
        """
        all_data = {1: c_site, 2: version, 3: p_name, 4: st_site, 5: custters_spec, 6: case_name,
            7: priority, 8: desc_file, 9: modify_time, 10: cp_all, 11: create_people, 12: ecn_no,
            13: customer_info, 14: file, 15: c_confirm, 16: workflow, 17: alter_cause, 18: alter_front, 
            19: alter_later, 20: pk_id, 21: ct, 22: confirm, 23: enabled, 24: copy_id,
            25: valid}
        """
        cu.update(version=all_data[2], p_name=all_data[3], st_site=all_data[4], custters_spec=all_data[5],
                  case_name=all_data[6], priority=all_data[7], desc_file=all_data[8], create_time=all_data[21],
                  alter_cause=all_data[17], alter_front=all_data[18], alter_later=all_data[19],
                  modify_time=modify_time, c_site=all_data[1], valid=all_data[25],
                  definer_name=all_data[10], create_people=all_data[11],
                  )

        file_id = []
        if all_data[14]:
            for i in all_data[14]:
                file_id.append(i['id'])
                for k, v in i.items():
                    if k == 'file_version' and i['file_version'] != None:
                        models.TbDrawingFile.objects.filter(id=int(i['id'])).update(file_version=i['file_version'])
            file_id.sort()

        pdf_list = []
        n = []
        for i in file_id:
            ni = i
            # 複製文件  如果上传新的文件，就不需要复制文件
            # sf = copy_data('TbDrawingFile', i)
            pl = models.TbDrawingFile.objects.filter(id=int(i))
            pl.update(customer_id=b.id, drawing_type_id=1, cus=1)
            for j in pl.values('id'):
                for key, v in j.items():
                    file_p_0 = pl.filter(file_type=0)  # 路徑只签合文件，不签合附件
                    if file_p_0:
                        file_p = file_p_0.values('file_path')[0]['file_path']
                        pl.update(sign_filepath=file_p)
                        new_pdf = {'href': settings.MEDIA_ROOT + str(file_p), "id": v}  # 形成的pdf
                        pdf_list.append(new_pdf)
                        n.append(settings.MEDIA_ROOT + str(file_p))
            up_p = models.TbDrawingFile.objects.get(id=ni)  # 拿回创建者和创建时间
            models.TbCustomerPaper.objects.filter(id=int(b.id)).update(uploader=up_p.uploader,
                                                                       upload_time=up_p.create_time)
        return b, n, pdf_list, re_id

    else:
        re_id = 0
        if m:
            if am.values('c_confirm')[0]['c_confirm'] == -1:
                models.TbCustomerPaper.objects.filter(id=m).update(c_confirm=-2)
            else:
                pass
        modify_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        m = all_data[20].values('id')[0]['id']
        # 立即失效
        if all_data[25]:
            # 如果valid爲1,修改上一版本圖紙的 enabled 爲0
            # copy_id = request.POST.get('copy_id')
            if all_data[24]:
                models.TbCustomerPaper.objects.filter(copy_id=all_data[24], c_confirm__gte=2).update(enabled=0)
        if all_data[14]:
            # 复制数据
            b = copy_data('TbCustomerPaper', m)
            # 更新客户信息
            mm = models.TbCustomerPaper.objects.filter(id=int(b.id))
            # 記錄變更次數
            c_info = models.TbCustomInfo.objects.filter(id=int(all_data[13]))
            mm.update(customer_info=int(c_info.values('id')[0]['id']))
            models.TbCustomerPaper.objects.filter(id=b.id).update(
                c_name=str(c_info.values('c_name')[0]['c_name']))
            models.TbCustomerPaper.objects.filter(id=b.id).update(
                c_type=str(c_info.values('c_type')[0]['c_type']))
            # 更新输入的字段
            cu = models.TbCustomerPaper.objects.filter(id=int(b.id))
            """
            all_data = {1: c_site, 2: version, 3: p_name, 4: st_site, 5: custters_spec, 6: case_name,
                7: priority, 8: desc_file, 9: modify_time, 10: cp_all, 11: create_people, 12: ecn_no,
                13: customer_info, 14: file, 15: c_confirm, 16: workflow, 17: alter_cause, 18: alter_front, 
                19: alter_later, 20: pk_id, 21: ct, 22: confirm, 23: enabled, 24: copy_id,
                25: valid}
            """
            cu.update(version=all_data[2], p_name=all_data[3], st_site=all_data[4], custters_spec=all_data[5],
                      case_name=all_data[6], priority=all_data[7], desc_file=all_data[8], create_time=all_data[21],
                      alter_cause=all_data[17], alter_front=all_data[18], alter_later=all_data[19],
                      modify_time=modify_time, c_site=all_data[1], valid=all_data[25], ecn_no=all_data[12],
                      definer_name=all_data[10], create_people=all_data[11],
                      c_confirm=int(all_data[15]),
                      )

            file_id = []
            if all_data[14]:
                for i in all_data[14]:
                    file_id.append(i['id'])
                    for k, v in i.items():
                        if k == 'file_version' and i['file_version'] != None:
                            models.TbDrawingFile.objects.filter(id=int(i['id'])).update(file_version=i['file_version'])

            file_id.sort()
            pdf_list = []
            n = []
            for i in file_id:
                # 複製文件
                ni = i
                sf = copy_data('TbDrawingFile', i)
                pl = models.TbDrawingFile.objects.filter(id=sf.id)
                pl.update(customer_id=b.id, drawing_type_id=1, cus=1)
                for j in pl.values('id'):
                    for key, v in j.items():
                        file_p_0 = pl.filter(file_type=0)  # 路徑只签合文件，不签合附件
                        if file_p_0:
                            file_p = file_p_0.values('file_path')[0]['file_path']
                            new_pdf = {'href': settings.MEDIA_ROOT + str(file_p), "id": v}  # 形成的pdf
                            pdf_list.append(new_pdf)
                            n.append(settings.MEDIA_ROOT + str(file_p))
                up_p = models.TbDrawingFile.objects.get(id=ni)  # 拿回创建者和创建时间
                models.TbCustomerPaper.objects.filter(id=int(b.id)).update(uploader=up_p.uploader,
                                                                      upload_time=up_p.create_time)
            return b, n, pdf_list, re_id


# c_post
def c_post(all_data):
    # 处理文件 (和工程圖紙處理方法不一樣)
    file_id = []
    if all_data[14]:
        for i in all_data[14]:
            file_id.append(i['id'])
            for k, v in i.items():
                if k == 'file_version' and i['file_version'] != None:
                    models.TbDrawingFile.objects.filter(id=int(i['id'])).update(file_version=i['file_version'])

        file_id.sort()

        if file_id:
            a = models.TbCustomerPaper.objects.create(
                ecn_no=all_data[12], version=all_data[2], p_name=all_data[3], create_people=all_data[11],
                st_site=all_data[4], valid=0, enabled=1, definer_name=all_data[10], c_site=all_data[1],
                custters_spec=all_data[5], case_name=all_data[6], desc_file=all_data[8],
                priority=all_data[7], create_time=all_data[9], c_confirm=all_data[15], file_version=all_data[17],
                modify_time=all_data[9], )
            mm = models.TbCustomerPaper.objects.filter(id=int(a.id))
            mm.update(copy_id=int(a.id))  # 将自动生成的id放入copy_id
            # 自動更新兩個值
            c_info = models.TbCustomInfo.objects.filter(id=int(all_data[13]))
            mm.update(customer_info_id=int(c_info.values('id')[0]['id']))
            models.TbCustomerPaper.objects.filter(id=a.id).update(
                c_name=str(c_info.values('c_name')[0]['c_name']))
            models.TbCustomerPaper.objects.filter(id=a.id).update(
                c_type=str(c_info.values('c_type')[0]['c_type']))

            pdf_list = []
            n = []
            for i in file_id:
                k = i
                pl = models.TbDrawingFile.objects.filter(id=int(i))
                # pl = models.TbDrawingFile.objects
                for j in pl.values('id'):
                    for key, v in j.items():
                        # 保证顺利签合，drawing_type_id赋值1
                        pl.filter(id=v).update(customer_id=int(a.id), drawing_type_id=1, cus=1)
                        # 路由籤合
                        file_p_0 = pl.filter(file_type=0)  # 路徑
                        if file_p_0:
                            file_p = file_p_0.values('file_path')[0]['file_path']
                            pl.update(sign_filepath=file_p)
                            new_pdf = {'href': settings.MEDIA_ROOT + str(file_p), "id": v}  # 形成的pdf
                            pdf_list.append(new_pdf)
                            n.append(settings.MEDIA_ROOT + str(file_p))
                up_p = models.TbDrawingFile.objects.get(id=k)  # 拿回创建者和创建时间
                models.TbCustomerPaper.objects.filter(id=int(a.id)).update(uploader=up_p.uploader,
                                                                          upload_time=up_p.create_time)
            return a, pdf_list, n
        if file_id == []:
            pdf_list = None
            n = None
            a = models.TbCustomerPaper.objects.create(
                ecn_no=all_data[12], version=all_data[2], p_name=all_data[3], create_people=all_data[11],
                st_site=all_data[4], valid=0, enabled=1, definer_name=all_data[10], c_site=all_data[1],
                custters_spec=all_data[5], case_name=all_data[6], desc_file=all_data[8],
                priority=all_data[7], create_time=all_data[9], c_confirm=all_data[15],
                modify_time=all_data[9], )
            mm = models.TbCustomerPaper.objects.filter(id=int(a.id))
            mm.update(copy_id=int(a.id))  # 将自动生成的id放入copy_id
            return a, pdf_list, n
    else:
        pdf_list = None
        n = None
        a = models.TbCustomerPaper.objects.create(
            ecn_no=all_data[12], version=all_data[2], p_name=all_data[3], create_people=all_data[11],
            st_site=all_data[4], valid=0, enabled=1, definer_name=all_data[10], c_site=all_data[1],
            custters_spec=all_data[5], case_name=all_data[6], desc_file=all_data[8],
            priority=all_data[7], create_time=all_data[9], c_confirm=all_data[15],
            modify_time=all_data[9], )
        mm = models.TbCustomerPaper.objects.filter(id=int(a.id))
        mm.update(copy_id=int(a.id))  # 将自动生成的id放入copy_id
        return a, pdf_list, n




# p_put
def p_put(all_data):
    print(10)
    modify_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

    """
    :param all_data: 
    :return: 
    """
    am = models.TbProjectPaper.objects.filter(id=int(all_data[27]))
    m = am.values('id')

    print(11)
    if str(all_data[29]) == 'true':
        print(12)
        re_id = 1
        b = models.TbProjectPaper.objects.get(id=m)
        data = {"id":all_data[30],"action":"pass"}
        requests.post(settings.DOWNLOAD_URL + 'api/workflow_approval',
                                         data=data, headers={'X-CSRFToken': all_data[31]})
        models.TbProjectPaper.objects.filter(id=b.id).update(
            cutter_type=all_data[23], stage_type=all_data[21], id_cutter_type=all_data[22], st_site=all_data[2],
            secrecy_level=all_data[24], id_stage_type=all_data[20], case_name=all_data[7], project_name=all_data[4],
            version=all_data[1], valid=all_data[15], create_people=all_data[16],
            definer_name=all_data[3], p_type=all_data[5], case_no=all_data[9], alter_cause=all_data[12],
            alter_front=all_data[13], alter_later=all_data[14], custters_spec=all_data[6], desc_file=all_data[11],
            priority=all_data[10],  modify_time=modify_time, file_version=all_data[28],
            enabled=1)
        if all_data[18]:
            # 获取现在数据库里面的所有文件的id，如果原来的id数据库里面有，
            # 将要复制文件，如果没有，就不用复制文件而直接加入现在工程图纸的id
            pdf_list = []
            n = []
            em = 'modify success.'
            for i in all_data[18]:
                k = i['id']
                fversion = i['file_version']
                # 保存文件  如果上传新的文件，就不需要复制文件
                id_list = []
                id_all = models.TbDrawingFile.objects.values('id')
                for one_id in id_all:
                    id_list.append(one_id['id'])
                if int(k) in id_list:  # 原有就要複製
                    sf = copy_data('TbDrawingFile', k)
                    models.TbDrawingFile.objects.filter(id=int(sf.id)).update(project_id=b.id, cus=0, file_version=fversion)
                    fileType = models.TbDrawingFile.objects.filter(id=int(sf.id)).values('file_type')[0][
                        'file_type']
                    if int(fileType) == 0:  # 0代表文件
                        if i['drawing_type_id'] == None or 'drawing_type_id' not in list(i.keys()):
                            em = '請輸入圖紙類別！'
                            a = 1 / 0
                            return 1, 1, 1, em
                        elif 'drawing_type_id' in list(i.keys()) and i['drawing_type_id'] != None:
                            dwt = models.TbDrawing.objects.filter(id=int(i['drawing_type_id'])).values(
                                'drawing_type')[0]['drawing_type']
                            models.TbDrawingFile.objects.filter(id=k).update(
                                drawing_type=i['drawing_type_id'], drawing_type_name=dwt, file_version=fversion)
                            models.TbProjectPaper.objects.filter(id=b.id).update(
                                id_drawing_type=i['drawing_type_id'], drawing_type=dwt)

                        if 'dev_type_id' in list(i.keys()) and i['dev_type_id'] != None:
                            dti = \
                                models.TbTypeDevice.objects.filter(id=int(i['dev_type_id'])).values('dev_type')[
                                    0]['dev_type']
                            models.TbDrawingFile.objects.filter(id=k).update(id_dev_type=i['dev_type_id'],
                                                                             dev_type=dti, file_version=fversion)
                            models.TbProjectPaper.objects.filter(id=b.id).update(id_dev_type=i['dev_type_id'],
                                                                                 dev_type=dti)
                    pl = models.TbDrawingFile.objects.filter(id=sf.id)
                    for j in pl.values('id'):
                        for key, v in j.items():
                            # 路由籤合
                            file_p_0 = pl.filter(file_type=0)  # 路徑
                            if file_p_0:
                                file_p = file_p_0.values('file_path')[0]['file_path']
                                new_pdf = {'href': settings.MEDIA_ROOT + str(file_p), "id": v}  # 形成的pdf
                                pdf_list.append(new_pdf)
                                n.append(settings.MEDIA_ROOT + str(file_p))
                    up_p = models.TbDrawingFile.objects.get(id=int(k))  # 拿回创建者和创建时间
                    models.TbProjectPaper.objects.filter(id=int(b.id)).update(uploader=up_p.uploader)
                    models.TbProjectPaper.objects.filter(id=int(b.id)).update(upload_time=up_p.create_time)
                else:
                    # sf = copy_data('TbDrawingFile', k)
                    models.TbDrawingFile.objects.filter(id=int(k)).update(project_id=b.id, cus=0, file_version=fversion)
                    fileType = models.TbDrawingFile.objects.filter(id=int(k)).values('file_type')[0]['file_type']
                    if int(fileType) == 0:  # 0代表文件
                        if i['drawing_type_id'] == None or 'drawing_type_id' not in list(i.keys()):
                            em = '請輸入圖紙類別！'
                            a = 1 / 0
                            return 1, 1, 1, em
                        elif 'drawing_type_id' in list(i.keys()) and i['drawing_type_id'] != None:
                            dwt = models.TbDrawing.objects.filter(id=int(i['drawing_type_id'])).values(
                                'drawing_type')[0]['drawing_type']
                            models.TbDrawingFile.objects.filter(id=k).update(
                                drawing_type=i['drawing_type_id'], drawing_type_name=dwt)
                            models.TbProjectPaper.objects.filter(id=b.id).update(
                                id_drawing_type=i['drawing_type_id'], drawing_type=dwt)

                        if 'dev_type_id' in list(i.keys()) and i['dev_type_id'] != None:
                            dti = \
                                models.TbTypeDevice.objects.filter(id=int(i['dev_type_id'])).values('dev_type')[
                                    0]['dev_type']
                            models.TbDrawingFile.objects.filter(id=k).update(id_dev_type=i['dev_type_id'],
                                                                             dev_type=dti)
                            models.TbProjectPaper.objects.filter(id=b.id).update(id_dev_type=i['dev_type_id'],
                                                                                 dev_type=dti)
                    pl = models.TbDrawingFile.objects.filter(id=int(k))
                    for j in pl.values('id'):
                        for key, v in j.items():
                            # 路由籤合
                            file_p_0 = pl.filter(file_type=0)  # 路徑
                            if file_p_0:
                                file_p = file_p_0.values('file_path')[0]['file_path']
                                pl.update(sign_filepath=file_p)
                                new_pdf = {'href': settings.MEDIA_ROOT + str(file_p), "id": v}  # 形成的pdf
                                pdf_list.append(new_pdf)
                                n.append(settings.MEDIA_ROOT + str(file_p))
                    up_p = models.TbDrawingFile.objects.get(id=int(k))  # 拿回创建者和创建时间
                    models.TbProjectPaper.objects.filter(id=int(b.id)).update(uploader=up_p.uploader)
                    models.TbProjectPaper.objects.filter(id=int(b.id)).update(upload_time=up_p.create_time)
            return b, pdf_list, n, em, re_id
    else:
        print(13)
        re_id = 0
        if m:
            if am.values('p_confirm')[0]['p_confirm'] == -1:
                models.TbProjectPaper.objects.filter(id=int(all_data[27])).update(p_confirm=-2)
            else:
                pass
        modify_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        """
        :param all_data: 
        :return: 
        """
        m = models.TbProjectPaper.objects.filter(id=int(all_data[27])).values('id')
        print(14)
        b = copy_data('TbProjectPaper', m[0]['id'])
        models.TbProjectPaper.objects.filter(id=b.id).update(
            cutter_type=all_data[23], stage_type=all_data[21], id_cutter_type=all_data[22], st_site=all_data[2],
            secrecy_level=all_data[24], id_stage_type=all_data[20], case_name=all_data[7], project_name=all_data[4],
            ecn_no=all_data[17], version=all_data[1], valid=all_data[15], create_people=all_data[16],
            definer_name=all_data[3], p_type=all_data[5], case_no=all_data[9], alter_cause=all_data[12],
            alter_front=all_data[13], alter_later=all_data[14], custters_spec=all_data[6], desc_file=all_data[11],
            priority=all_data[10], p_confirm=all_data[19], modify_time=modify_time, file_version=all_data[28],
            enabled=1)
        # 文件
        print(15)
        if all_data[18]:
            pdf_list = []
            n = []
            em = 'modify success.'
            for i in all_data[18]:
                k = i['id']
                for mk, v in i.items():
                    if mk == 'file_version':
                        fversion = i['file_version']
                        models.TbDrawingFile.objects.filter(id=k).update(file_version=fversion)
                    else:
                        fversion = None

                # 保存文件

                sf = copy_data('TbDrawingFile', k)
                models.TbDrawingFile.objects.filter(id=int(sf.id)).update(project_id=b.id, cus=0)
                fileType = models.TbDrawingFile.objects.filter(id=int(sf.id)).values('file_type')[0]['file_type']
                if int(fileType) == 0:  # 0代表文件
                    if i['drawing_type_id'] == None or 'drawing_type_id' not in list(i.keys()):
                        em = '請輸入圖紙類別！'
                        a = 1 / 0
                        return 1, 1, 1, em
                    elif 'drawing_type_id' in list(i.keys()) and i['drawing_type_id'] != None:
                        dwt = models.TbDrawing.objects.filter(id=int(i['drawing_type_id'])).values(
                            'drawing_type')[0]['drawing_type']
                        models.TbDrawingFile.objects.filter(id=k).update(
                            drawing_type=i['drawing_type_id'], drawing_type_name=dwt)
                        models.TbProjectPaper.objects.filter(id=b.id).update(
                            id_drawing_type=i['drawing_type_id'], drawing_type=dwt)

                    if 'dev_type_id' in list(i.keys()) and i['dev_type_id'] != None:
                        dti = \
                            models.TbTypeDevice.objects.filter(id=int(i['dev_type_id'])).values('dev_type')[
                                0]['dev_type']
                        models.TbDrawingFile.objects.filter(id=k).update(id_dev_type=i['dev_type_id'],
                                                                         dev_type=dti)
                        models.TbProjectPaper.objects.filter(id=b.id).update(id_dev_type=i['dev_type_id'],
                                                                             dev_type=dti)
                pl = models.TbDrawingFile.objects.filter(id=sf.id)
                for j in pl.values('id'):
                    for key, v in j.items():
                        # 路由籤合
                        file_p_0 = pl.filter(file_type=0)  # 路徑
                        if file_p_0:
                            file_p = file_p_0.values('file_path')[0]['file_path']
                            new_pdf = {'href': settings.MEDIA_ROOT + str(file_p), "id": v}  # 形成的pdf
                            pdf_list.append(new_pdf)
                            n.append(settings.MEDIA_ROOT + str(file_p))
                up_p = models.TbDrawingFile.objects.get(id=int(k))  # 拿回创建者和创建时间
                models.TbProjectPaper.objects.filter(id=int(b.id)).update(uploader=up_p.uploader)
                models.TbProjectPaper.objects.filter(id=int(b.id)).update(upload_time=up_p.create_time)
            return b, pdf_list, n, em, re_id


# p_post
def p_post(all_data):
    create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    """
    all_data = {1: version, 2: st_site, 3: definer_name, 4: project_name, 5: p_type, 6: custters_spec,
                7: case_name, 8: secrecy_level, 9: case_no, 10: priority, 11: desc_file,
                12: cc, 13: create_people, 14: ecn_no, 15: file_id,
                16: p_confirm, 17: pt_id, 18: ps, 19: kf_id, 20: kt, 21: secrecy_level
                }
    :param all_data: 
    :return: 
    """
    b = models.TbProjectPaper.objects.create(
        cutter_type=all_data[20], stage_type=all_data[18], id_cutter_type=all_data[19], st_site=all_data[2],
        secrecy_level=all_data[21], id_stage_type=all_data[17], case_name=all_data[7], project_name=all_data[4],
        ecn_no=all_data[14], version=all_data[1], create_people=all_data[13],
        definer_name=all_data[3], p_type=all_data[5], case_no=all_data[9],
        custters_spec=all_data[6], desc_file=all_data[11], valid=0, enabled=1,
        priority=all_data[10], p_confirm=all_data[16], modify_time=create_time, create_time=create_time,
        file_version=all_data[22],
        )
    pp_info = models.TbProjectPaper.objects.filter(id=b.id)
    pp_info.update(id_copy=b.id)  # 复制id
    # 文件
    if all_data[15]:
        pdf_list = []
        n = []
        em = 'create success.'
        for i in all_data[15]:
            k = i['id']
            # 2018/4/19
            for mk, v in i.items():
                if mk == 'file_version':
                    fversion = i['file_version']
                    models.TbDrawingFile.objects.filter(id=int(k)).update(file_version=fversion)
                else:
                    fversion = None

            models.TbDrawingFile.objects.filter(id=int(k)).update(project_id=b.id, cus=0)
            fileType = models.TbDrawingFile.objects.filter(id=int(k)).values('file_type')[0]['file_type']
            if int(fileType) == 0:  # 0代表文件
                if 'drawing_type_id' not in list(i.keys()) or i['drawing_type_id'] == None:
                    em = '請輸入圖紙類別！'
                    a = 1/0
                    return 1,1,1,em
                elif 'drawing_type_id' in list(i.keys()) and i['drawing_type_id'] != None:
                    dwt = models.TbDrawing.objects.filter(id=int(i['drawing_type_id'])).values(
                        'drawing_type')[0]['drawing_type']
                    models.TbDrawingFile.objects.filter(id=k).update(
                        drawing_type=i['drawing_type_id'], drawing_type_name=dwt)
                if 'dev_type_id' in list(i.keys()) and i['dev_type_id'] != None:
                    dti = \
                        models.TbTypeDevice.objects.filter(id=int(i['dev_type_id'])).values('dev_type')[
                            0]['dev_type']
                    models.TbDrawingFile.objects.filter(id=k).update(id_dev_type=i['dev_type_id'],
                                                                     dev_type=dti)
            pl = models.TbDrawingFile.objects.filter(id=k)
            for j in pl.values('id'):
                for key, v in j.items():
                    # 路由籤合
                    file_p_0 = pl.filter(file_type=0)  # 路徑
                    if file_p_0:
                        file_p = file_p_0.values('file_path')[0]['file_path']
                        pl.update(sign_filepath=file_p)
                        new_pdf = {'href': settings.MEDIA_ROOT + str(file_p), "id": v}  # 形成的pdf
                        pdf_list.append(new_pdf)
                        n.append(settings.MEDIA_ROOT + str(file_p))
            up_p = models.TbDrawingFile.objects.get(id=int(k))  # 拿回创建者和创建时间
            models.TbProjectPaper.objects.filter(id=int(b.id)).update(uploader=up_p.uploader, upload_time=up_p.create_time)
        return b, pdf_list, n, em
    elif all_data[15] == []:
        pdf_list = None
        n = None
        em = 'create success.'
        return b, pdf_list, n, em

# combination sql
def conSql(TableName, number):
    sfw = "SELECT * FROM `{0}` WHERE ".format(TableName)
    sqlList = []
    kl = ''
    for i in range(number):
        strsql = "(c_name LIKE LIKE '%{0}%' OR c_name_short LIKE '%{0}%' OR c_type LIKE '%{0}%')".format(i)
        sr = strsql.replace('%{0}%'.format(i), '%{' + '{0}'.format(i) + '}%')
        sqlList.append(sr)
    for k in sqlList:
        kl = kl + ' and ' + k
    return sfw + kl[5:]

def conQ(number):
    kl = ''
    sqlList = []
    for i in range(number):
        strQ = 'Q(c_name__contains="%{0}%") | Q(c_num__contains="%{0}%") | Q(c_type__contains="%{0}%") | Q(c_site__contains=%{0}%)'.format(i)
        sr = strQ.replace('%{0}%'.format(i), '%{' + '{0}'.format(i) + '}%')
        sqlList.append(sr)
    for k in sqlList:
        kl = kl + ' | ' + k
    return kl[2:]


def conQ(number):
    kl = ''
    sqlList = []
    myfilter = '.filter('
    for i in range(number):
        strQ = 'Q(c_name__contains=%{0}%) | Q(c_num__contains=%{0}%) | Q(c_type__contains=%{0}%) | Q(c_site__contains=%{0}%)'.format(i)
        sr = strQ.replace('%{0}%'.format(i), '{' + '{0}'.format(i) + '}')
        sf = myfilter + sr + ')'
        sqlList.append(sf)
    for k in sqlList:
        kl = kl + k
    return kl

def formatQ(formatlist):
    f = '.format('
    kl = ''
    sqlList = []
    for i in formatlist:
        if type(i) == str:
            sqlList.append('"' + "'" + '{0}'.format(i) + "'" + '"')
        else:
            sqlList.append(i)
    for k in sqlList:
        kl = kl + ' , ' + str(k)
    return f + kl[3:] + ')'

def comb(formatlist):
    try:
        num = len(formatlist)
        r1 = conQ(num)
        r2 = formatQ(formatlist)
        res = "'" + r1 + "'" + r2
        d = eval(res)
        return d
    except Exception as e:
        return e